package com.base.logistics.sf.request;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import com.base.core.utils.JacksonUtils;
import com.base.logistics.config.SfConfig;
import com.base.logistics.sf.bean.RequestParams;
import com.base.logistics.sf.bean.Response;
import com.base.logistics.sf.bean.Result;
import com.base.logistics.sf.enums.SfErrorMsgEnum;
import com.base.logistics.utils.SfGsonBuilder;

/**
 * <pre>
 * 顺丰快递api接口实现
 * </pre>
 * @since 2021-02-14
 */
public class SfApiRequestConfig implements SfRequestConfig {

    private SfConfig sfConfig;

    @Override
    public void setConfig(SfConfig config) {
        this.sfConfig = config;
    }

    @Override
    public SfConfig getConfig() {
        return this.sfConfig;
    }

    @Override
    public String post(RequestParams request) throws Exception {
        request.build(this.sfConfig);
        try {
            String result = HttpRequest.post(this.sfConfig.getUrl())
                    .form(request)
                    .header("Content-type","application/x-www-form-urlencoded;charset=UTF-8")
                    .execute().body();

            if(StrUtil.isBlank(result)){
                throw new Exception("无响应内容");
            }
            Response response = Response.fromJson(result);

            if(SfErrorMsgEnum.CODE_A1000.getCode().equals(response.getApiResultCode())){
                Result data = Result.fromJson(response.getApiResultData());
                if(data.getSuccess()){
                    return SfGsonBuilder.create().toJson(data);
                }
                throw new Exception(data.getErrorMsg());
            }
            throw new Exception(response.getApiErrorMsg());
        }catch (HttpException e){
            throw new Exception("接口请求发生错误");
        }
    }
}
